package com.wh.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wh.basic.utils.WxConstants;
import com.wh.basic.vo.AjaxResult;
import com.wh.org.exception.BusinessException;
import com.wh.user.dao.IUserDao;
import com.wh.user.dao.LoginInfoDao;
import com.wh.user.dao.WxuserDao;
import com.wh.user.dto.WxBinderDto;
import com.wh.user.pojo.LoginInfo;
import com.wh.user.pojo.User;
import com.wh.user.pojo.Wxuser;
import com.wh.user.service.IWxuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WxuserServiceimpl implements IWxuserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private LoginInfoDao loginInfoDao;
    @Autowired
    private WxuserDao wxuserDao;

    /**
     * 微信绑定逻辑
     *
     * @param binderDto 微信绑定参数
     * @return
     */
    @Transactional
    @Override
    public AjaxResult wechatBinder(WxBinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accessToken = binderDto.getAccessToken();
        String openid = binderDto.getOpenid();
        //校验
        //1.校验 - 空置校验
        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(verifyCode)) {
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get("binder:" + phone);
        if (redisCode == null) {
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())) {
            throw new BusinessException("验证码错误");
        }

        //4.获取用户信息 - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        String jsonStr = com.baidu.ai.aip.utils.HttpUtil.httpGet(url);

        //5.解析用户信息
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        openid = jsonObject.get("openid").toString();
        String nickname = jsonObject.get("nickname").toString();
        Integer sex = (Integer) jsonObject.get("sex");
        String address = "" + jsonObject.get("country") + jsonObject.get("province") + jsonObject.get("city");
        String headimgurl = "" + jsonObject.get("headimgurl");
        String unionid = "" + jsonObject.get("unionid");

        //6.查询手机号是否存在(同一个手机号不能绑定多个微信)
        User user = userDao.selectOne(new QueryWrapper<User>().eq("phone", binderDto.getPhone()));
        if (user != null){
            throw new BusinessException("手机号已注册,请检查后重试!");
        }

        //7.添加登录用户信息
        LoginInfo logininfo = new LoginInfo();
        logininfo.setUsername(binderDto.getPhone());
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfo.setPhone(binderDto.getPhone());
        String salt = IdUtil.fastSimpleUUID();
        logininfo.setSalt(salt);
        String password = SecureUtil.md5("123456" + salt);
        logininfo.setPassword(password);
        loginInfoDao.insert(logininfo);

        //8.添加用户信息
        User newUser = BeanUtil.copyProperties(logininfo, User.class,"id");
        newUser.setLogininfoId(logininfo.getId());
        newUser.setState(1);
        newUser.setHeadImg(headimgurl);
        newUser.setCreatetime(LocalDateTime.now());
        userDao.insert(newUser);

        //9.添加微信用户信息
        Wxuser wxuser = new Wxuser();
        wxuser.setAddress(address);
        wxuser.setHeadimgurl(headimgurl);
        wxuser.setNickname(nickname);
        wxuser.setSex(sex);
        wxuser.setOpenid(openid);
        wxuser.setUnionid(unionid);
        wxuser.setUserId(newUser.getId());
        wxuserDao.insert(wxuser);

        //10.做免密登录(把数据返回给前台用来展示用户名)
        String token = IdUtil.fastSimpleUUID();
        logininfo.setPassword(null);     //去掉密码和盐值 - 安全
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return AjaxResult.me().setResultObj(map);
    }
}
